# -*- coding: utf-8 -*-
import re
from datetime import datetime, timedelta
from metlib.shell.fileutil import *
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse, \
    HttpResponseNotFound, Http404, \
    HttpResponseServerError, HttpResponseNotAllowed, \
    HttpResponseBadRequest
from metlib.misc.datatype import Null
from metlib.misc.misc import gen_uuid8, parse_bool
from weblib.django.http.response import *
from weblib.django.setting import get_setting
from .data_utils import *
from datasets.dataset_molds.FG_WRF_S3.fg_wrf_common import fgwrf_zh_varname_d, fgwrf_zh_subset_d, fgwrf_units_d, \
    fgwrf_pt_suggest_range_d


# info={level=1,2,3,4,type=original,round, lat=xxx,lon=xxx} 4为原始层。
# 无可用数据时的http response.
def get_point_info(request, *args, **kwargs):
    try:
        if request.method not in ('GET', 'POST'):
            return HttpResponseNotAllowed(['GET', 'POST'])
        if request.method == 'GET':
            info = request.GET.dict()
        else:
            info = request.POST.dict()
        level = int(info["level"])
        type = info["type"]
        result_dict = {
            "status": "ok",
            "objects": []
        }
        # 按照级别数据类型获取点详细信息
        if level == 1 and type == "round":
            data = MapPointData.get_round_frist()
        if level == 5 and type == "chinaoriginal":
            data = serializers.serialize("json", MapPointData.get_china_station_data())
        else:
            lat = info["lat"]
            lon = info["lon"]
            if level == 0 and type == "original":
                lat_end = info["lat_end"]
                lon_end = info["lon_end"]
                data = MapPointData.get_original(frist_lat=lat, frist_lon=lon, end_lat=lat_end, end_lon=lon_end)
            elif level == 1 and type == "original":
                data = MapPointData.get_frist_original(round_frist_lat=lat, round_frist_lon=lon)
            elif level == 2 and type == "round":
                data = MapPointData.get_round_sec(round_frist_lat=lat, round_frist_lon=lon)
            elif level == 2 and type == "original":
                data = MapPointData.get_sec_original(round_sec_lat=lat, round_sec_lon=lon)
            elif level == 3 and type == "round":  # 数据较少
                data = MapPointData.get_round_thrid(round_sec_lat=lat, round_sec_lon=lon)
            elif level == 3 and type == "original":
                data = MapPointData.get_thrid_original(round_thrid_lat=lat, round_thrid_lon=lon)
            elif level == 4 and type == "round":
                pass
            elif level == 4 and type == "original":
                data = MapPointData.get_original_data(lat, lon)
        result_dict["objects"] = data
        return JsonResponse(result_dict)
    except Exception as e:
        result_dict = {
            "status": "Error",
            "reason": unicode(e),
            "objects": []
        }
    return ExceptionJsonResponse(result_dict)


# uri	"point/PY/rh/2016/1" 级别一-
# 无可用数据时的http response.
def get_point_data(request, uri, *args, **kwargs):
    try:
        parts = uri.split('/')
        datatype = parts[1]
        if datatype == "PT":
            return get_point_pt_data(request, uri, *args, **kwargs)
        elif datatype == "PM":
            return get_point_pm_data(request, uri, *args, **kwargs)
        elif datatype == "PD":
            return get_point_pd_data(request, uri, *args, **kwargs)
        elif datatype == "PY":
            return get_point_py_data(request, uri, *args, **kwargs)
        elif datatype == "ALL":
            return get_point_ALL_data(request, uri, *args, **kwargs)
        elif datatype == "chart":
            return get_point_chart_data(request, uri, *args, **kwargs)

    except Exception as e:
        result_dict = {
            "status": "Error",
            "reason": unicode(e),
            "objects": []
        }
    return ExceptionJsonResponse(result_dict)
# point数据
# area
# littler 数据结构
# type	"datapack"
# uri	"point/ALL/?lat=XX&lon=XX&betdt=1990010100enddt=1990010100" 级别一-
# 无可用数据时的http response.
def get_point_ALL_data(request, uri, *args, **kwargs):
    try:
        if request.method not in ('GET', 'POST'):
            return HttpResponseNotAllowed(['GET', 'POST'])
        if request.method == 'GET':
            info = request.GET.dict()
        else:
            info = request.POST.dict()
        parts = uri.split('/')
        year = parts[2]
        # datetime.strptime(self.date_char, "%Y%m%d%H%M%S")
        info["begdt"] = datetime.strptime(info["begdt"], "%Y%m%d%H")
        info["enddt"] = datetime.strptime(info["enddt"], "%Y%m%d%H")
        begdt = info["begdt"].strftime("%Y-%m-%d %H:%M:%S")
        enddt = info["enddt"].strftime("%Y-%m-%d %H:%M:%S")
        lat = info["lat"]
        lon = info["lon"]
        pt_datas = MapLitterData.get_point_pt_data(lat, lon, begdt, enddt)
        data_dict = {"total": 0, "data": []}
        for data in pt_datas:
            data_dict["total"] = data_dict["total"] + 1
            data_info = {}
            data_info["source"] = data.source
            data_info["elevation"] = data.elevation
            data_info["num_valid_fields"] = data.num_valid_fields
            data_info["num_error"] = data.num_error
            data_info["num_warning"] = data.num_warning
            data_info["seq_num"] = data.seq_num
            data_info["num_dups"] = data.num_dups
            data_info["is_sound"] = data.is_sound
            data_info["bogus"] = data.bogus
            data_info["discard"] = data.discard
            data_info["sut"] = data.sut
            data_info["julian"] = data.julian
            data_info["date_char"] = data.date_char
            data_info["slp"] = data.slp
            data_info["slp_qc"] = data.slp_qc
            data_info["ref_pres"] = data.ref_pres
            data_info["ref_pres_qc"] = data.ref_pres_qc
            data_info["ground_t"] = data.ground_t
            data_info["ground_t_qc"] = data.ground_t_qc
            data_info["psfc"] = data.psfc
            data_info["psfc_qc"] = data.psfc_qc
            data_info["precip"] = data.precip
            data_info["precip_qc"] = data.precip_qc
            data_info["t_max"] = data.t_max
            data_info["t_max_qc"] = data.t_max_qc
            data_info["t_min"] = data.t_min
            data_info["t_min_qc"] = data.t_min_qc
            data_info["t_min_night"] = data.t_min_night
            data_info["t_min_night_qc"] = data.t_min_night_qc
            data_info["cloud_cvr"] = data.cloud_cvr
            data_info["cloud_cvr_qc"] = data.cloud_cvr_qc
            data_info["update_dt"] = data.update_dt
            data_info["level_info"] = data.level_info
            data_dict["data"].append(data_info)
        return JsonResponse(data_dict)

    except Exception as e:
        result_dict = {
            "status": "Error",
            "reason": unicode(e),
            "objects": []
        }
    return ExceptionJsonResponse(result_dict)


# point数据
# area
# littler 数据结构
# type	"datapack"
# uri	"point/chart/?lat=XX&lon=XX&betdt=1990010100enddt=1990010100" 级别一-
# 无可用数据时的http response.
def get_point_chart_data(request, uri, *args, **kwargs):
    try:
        if request.method not in ('GET', 'POST'):
            return HttpResponseNotAllowed(['GET', 'POST'])
        if request.method == 'GET':
            info = request.GET.dict()
        else:
            info = request.POST.dict()
        info["begdt"] = datetime.strptime(info["begdt"], "%Y%m%d%H")
        info["enddt"] = datetime.strptime(info["enddt"], "%Y%m%d%H")
        begdt = info["begdt"].strftime("%Y-%m-%d %H:%M:%S")
        enddt = info["enddt"].strftime("%Y-%m-%d %H:%M:%S")
        station_id = info["station_id"]
        pt_datas = MapLitterData.get_point_for_stationid(station_id, begdt, enddt)
        var_level_dict = {}
        for data in pt_datas:
            level_info = json.loads(data.level_info)
            for level_data in level_info:
                lv = level_data["level"]
                if not var_level_dict.has_key(lv):
                    var_level_dict[lv] = {}
                # var_level_dict["key"] = lv
                for k, v in level_data.items():
                    if k == "little_data_id" or k == "level":
                        continue

                    if var_level_dict[lv].has_key(k):
                        if v == "" or v == -888888.0 or v == 999999.0 or v == -888888 or v == -999999:
                            v = None
                        if v is not None:
                            if k == 'temp' or k == 'dew':
                                v = v - 273.15
                        chart_data = [datetime_timestamp_dt(data.date_char) * 1000, v]
                        var_level_dict[lv][k]["data"].append(chart_data)
                    else:
                        var_level_dict[lv][k] = {}
                        var_level_dict[lv][k]["data"] = []
                        var_level_dict[lv][k]["name"] = k
                        var_level_dict[lv][k]["zh_name"] = fgwrf_zh_varname_d.get(k, k)
                        if v == "" or v == -888888.0 or v == 999999.0 or v == -888888 or v == -999999:
                            v = None
                        if v is not None:
                            if k == 'temp' or k == 'dew':
                                v = v - 273.15
                        chart_data = [datetime_timestamp_dt(data.date_char) * 1000, v]
                        var_level_dict[lv][k]["data"].append(chart_data)
                        var_level_dict[lv][k]["units"] = fgwrf_units_d.get(k)
        return JsonResponse(var_level_dict)

    except Exception as e:
        result_dict = {
            "status": "Error",
            "reason": unicode(e),
            "objects": []
        }
    return ExceptionJsonResponse(result_dict)


# point数据
# area
# littler 数据结构
# type	"datapack"
# uri	"point/PT/rh/1990/?lat=XXlon=XX&level=XX" 级别一-
# 无可用数据时的http response.
def get_point_pt_data(request, uri, *args, **kwargs):
    try:
        if request.method not in ('GET', 'POST'):
            return HttpResponseNotAllowed(['GET', 'POST'])
        if request.method == 'GET':
            info = request.GET.dict()
        else:
            info = request.POST.dict()
        parts = uri.split('/')
        # datatype = parts[1]
        varname = parts[2]
        year = parts[3]
        begdt = "%s-01-01 00:00:00" % year
        enddt = "%s-12-31 23:59:59" % year
        lat = info["lat"]
        lon = info["lon"]
        level = info["level"]
        pt_datas = MapLitterData.get_point_pt_data(lat, lon, begdt, enddt)
        level_info = {}
        datachars = []
        var_datas = []
        for data in pt_datas:
            level_info = json.loads(data.level_info)
            var_data = None
            for level_data in level_info:
                # level[varname]
                if level_data["level"] == int(level):
                    level_data[varname] = level_data.pop(varname, None)
                    var_data = level_data[varname]
            datachars.append(datetime_timestamp_dt(data.date_char))
            var_datas.append(var_data)
        result_dict = {}
        result_dict["type"] = "datapack"
        result_dict["uri"] = uri
        result_dict["contents"] = {}
        result_dict["contents"][uri] = {}
        result_dict["contents"][uri]["info"] = {'varname': varname, 'type': "", "subset": 'PT',
                                                'zh_varname': fgwrf_zh_varname_d.get(varname, varname)}
        result_dict["contents"][uri]["type"] = "dataunit"
        result_dict["contents"][uri]["coords"] = {'varname': varname, 'type': "",
                                                  'zh_varname': fgwrf_zh_varname_d.get(varname, varname)}
        result_dict["contents"][uri]["uri"] = uri
        result_dict["contents"][uri]["data"] = {}
        result_dict["contents"][uri]["data"]["utc_offset"] = 8
        result_dict["contents"][uri]["data"]["dts"] = datachars
        result_dict["contents"][uri]["data"]["interval"] = 3600
        result_dict["contents"][uri]["data"]["suggest_range"] = fgwrf_pt_suggest_range_d.get(varname, (None, None))
        result_dict["contents"][uri]["data"]["values"] = var_datas
        result_dict["contents"][uri]["data"]["units"] = fgwrf_units_d.get(varname)
        result_dict["contents"][uri]["data"]["begdt"] = datetime_timestamp(begdt)

        return JsonResponse(result_dict)

    except Exception as e:
        result_dict = {
            "status": "Error",
            "reason": unicode(e),
            "objects": []
        }
    return ExceptionJsonResponse(result_dict)


# point数据
# area
# littler 数据结构
# type	"datapack"
# uri	"point/PM/rh/2016/1" 级别一-
# contents	Object
# tags	Object
# 无可用数据时的http response.
def get_point_pm_data(request, uri, *args, **kwargs):
    try:
        if request.method not in ('GET', 'POST'):
            return HttpResponseNotAllowed(['GET', 'POST'])
        if request.method == 'GET':
            info = request.GET.dict()
        else:
            info = request.POST.dict()
        parts = uri.split('/')
        datatype = parts[1]
        varname = parts[2]
        year = parts[3]
        level = parts[4]
        result_dict = {}
        begdt = "%s01-01 00:00:00" % year
        result_dict["type"] = "datapack"
        result_dict["uri"] = uri
        result_dict["contents"] = {}
        result_dict["contents"][uri] = {}
        result_dict["contents"][uri]["info"] = {'varname': varname, 'type': "", 'zh_varname': ""}
        result_dict["contents"][uri]["type"] = "dataunit"
        result_dict["contents"][uri]["coords"] = {'varname': varname, 'type': "", 'zh_varname': ""}
        result_dict["contents"][uri]["uri"] = uri
        result_dict["contents"][uri]["data"] = {}
        result_dict["contents"][uri]["data"]["utc_offset"] = 8
        result_dict["contents"][uri]["data"]["values"] = []
        result_dict["contents"][uri]["data"]["units"] = ""
        result_dict["contents"][uri]["data"]["categories"] = []
        result_dict["contents"][uri]["data"]["zh-categories-name"] = "月统计"

    except Exception as e:
        result_dict = {
            "status": "Error",
            "reason": unicode(e),
            "objects": []
        }
    return ExceptionJsonResponse(result_dict)


# point数据
# area
# littler 数据结构
# type	"datapack"
# uri	"point/PY/summary/2016/1" 级别一-
# contents	Object
# tags	Object
# 无可用数据时的http response.
def get_point_py_data(request, uri, *args, **kwargs):
    try:
        if request.method not in ('GET', 'POST'):
            return HttpResponseNotAllowed(['GET', 'POST'])
        if request.method == 'GET':
            info = request.GET.dict()
        else:
            info = request.POST.dict()
        parts = uri.split('/')
        varname = parts[2]
        year = parts[3]
        begdt = "%s-01-01 00:00:00" % year
        enddt = "%s-12-31 23:59:59" % year
        lat = info["lat"]
        lon = info["lon"]
        level = info["level"]
        pt_datas = MapLitterData.get_point_pt_data(lat, lon, begdt, enddt)
        level_info = {}
        datachars = []
        var_datas = {}
        var_namelist = {}
        for data in pt_datas:
            level_info = json.loads(data.level_info)
            var_data = None
            for level_data in level_info:
                if level_data["level"] == int(level):
                    if varname == "summary":
                        num = 0
                        for k, v in level_data.items():
                            var_namelist[str(num)] = k
                            num = num + 1
                            var_datas[k] = {}
                            var_datas[k]["values"] = var_datas[k].pop("values", "")
                            if var_datas[k]["values"] != "" and var_datas[k]["values"] != -888888.0 and var_datas[k][
                                "values"] != 999999.0:
                                var_datas[k]["values"] = (var_datas[k]["values"] + v) / 2
                            var_datas[k]["zh_name"] = fgwrf_zh_varname_d.get(k, k)
                            var_datas[k]["units"] = fgwrf_units_d.get(k, k)
        result_dict = {}
        result_dict["type"] = "datapack"
        result_dict["uri"] = uri
        result_dict["contents"] = {}
        result_dict["contents"][uri] = {}
        result_dict["contents"][uri]["info"] = {'varname': varname,
                                                'zh_varname': fgwrf_zh_subset_d.get(varname, varname),
                                                'level': info["level"], "time": year, "subset": 'PY'}
        result_dict["contents"][uri]["info"]["sub_varnames"] = var_namelist
        result_dict["contents"][uri]["type"] = "dataunit"
        result_dict["contents"][uri]["coords"] = {'varname': varname, 'type': "",
                                                  'zh_varname': fgwrf_zh_subset_d.get(varname, varname)}
        result_dict["contents"][uri]["uri"] = uri
        result_dict["contents"][uri]["data"] = var_datas

        return JsonResponse(result_dict)
    except Exception as e:
        result_dict = {
            "status": "Error",
            "reason": unicode(e),
            "objects": []
        }
    return ExceptionJsonResponse(result_dict)


# point数据
# area
# littler 数据结构
# type	"datapack"
# uri	"point/PD/rh/2016/1" 级别一-
# contents	Object
# tags	Object
# 无可用数据时的http response.
def get_point_pd_data(request, uri, *args, **kwargs):
    try:
        if request.method not in ('GET', 'POST'):
            return HttpResponseNotAllowed(['GET', 'POST'])
        if request.method == 'GET':
            info = request.GET.dict()
        else:
            info = request.POST.dict()
        parts = uri.split('/')
        datatype = parts[1]
        varname = parts[2]
        year = parts[3]
        level = parts[4]
        result_dict = {}
        begdt = "%s-01-01 00:00:00" % year
        result_dict["type"] = "datapack"
        result_dict["uri"] = uri
        result_dict["contents"] = {}
        result_dict["contents"][uri] = {}
        result_dict["contents"][uri]["info"] = {'varname': varname, 'type': "",
                                                'zh_varname': fgwrf_zh_subset_d.get(varname, varname),
                                                'level': info["level"], "time": year, "subset": 'PD'}
        result_dict["contents"][uri]["type"] = "dataunit"
        result_dict["contents"][uri]["coords"] = {'varname': varname, 'type': "", 'zh_varname': ""}
        result_dict["contents"][uri]["uri"] = uri
        result_dict["contents"][uri]["data"] = {}
        result_dict["contents"][uri]["data"]["utc_offset"] = 8
        result_dict["contents"][uri]["data"]["dts"] = []
        result_dict["contents"][uri]["data"]["interval"] = 3600
        result_dict["contents"][uri]["data"]["suggest_range"] = []
        result_dict["contents"][uri]["data"]["values"] = []
        result_dict["contents"][uri]["data"]["units"] = ""
        result_dict["contents"][uri]["data"]["begdt"] = datetime_timestamp(begdt)

    except Exception as e:
        result_dict = {
            "status": "Error",
            "reason": unicode(e),
            "objects": []
        }
    return ExceptionJsonResponse(result_dict)

def get_area_data(request, uri, *args, **kwargs):
    pass
